#!/bin/bash

. /start-utils

if [ -n "$OPS" ]; then
  log "Setting/adding ops"
  rm -rf ops.txt.converted
  echo $OPS | awk -v RS=, '{print}' > ops.txt
fi

if [ -n "$WHITELIST" ]; then
  log "Setting whitelist"
  rm -rf white-list.txt.converted
  echo $WHITELIST | awk -v RS=, '{print}' > white-list.txt
fi

if [ -n "$ICON" -a ! -e server-icon.png ]; then
  log "Using server icon from $ICON..."
  # Not sure what it is yet...call it "img"
  curl -sSL -o /tmp/icon.img $ICON
  specs=$(identify /tmp/icon.img | awk '{print $2,$3}')
  if [ "$specs" = "PNG 64x64" ]; then
    mv /tmp/icon.img /data/server-icon.png
  else
    log "Converting image to 64x64 PNG..."
    convert /tmp/icon.img -resize 64x64! /data/server-icon.png
  fi
fi

# Make sure files exist and are valid JSON (for pre-1.12 to 1.12 upgrades)
log "Checking for JSON files."
JSON_FILES=$(find . -maxdepth 1 -name '*.json')
for j in $JSON_FILES; do
  if [[ $(cat $j | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//') == "" ]]; then
    log "Fixing JSON $j"
    echo '[]' > $j
  fi
done


# If any modules have been provided, copy them over
mkdir -p /data/mods
if [ -d /mods ]; then
  log "Copying any mods over..."
  rsync -a --out-format="update:%f:Last Modified %M" --prune-empty-dirs --update /mods /data
fi

[ -d /data/config ] || mkdir /data/config
for c in /config/*
do
  if [ -f "$c" ]; then
    log Copying configuration `basename "$c"`
    cp -rf "$c" /data/config
  fi
done

mkdir -p /data/plugins
if [ "$TYPE" = "SPIGOT" ]; then
  if [ -d /plugins ]; then
    log "Copying any Bukkit plugins over..."
    # Copy plugins over using rsync to allow deeply nested updates of plugins
    # only updates files if the source file is newer and print updated files
    rsync -a --out-format="update:%f:Last Modified %M" --prune-empty-dirs --update /plugins /data
  fi
fi

EXTRA_ARGS=""
# Optional disable console
if [[ ${CONSOLE} = false || ${CONSOLE} = FALSE ]]; then
  EXTRA_ARGS+="--noconsole"
fi

# Optional disable GUI for headless servers
if [[ ${GUI} = false || ${GUI} = FALSE ]]; then
  EXTRA_ARGS="${EXTRA_ARGS} nogui"
fi

# put these prior JVM_OPTS at the end to give any memory settings there higher precedence
log "Setting initial memory to ${INIT_MEMORY:=${MEMORY}} and max to ${MAX_MEMORY:=${MEMORY}}"

expandedDOpts=
if [ -n "$JVM_DD_OPTS" ]; then
      for dopt in $JVM_DD_OPTS
      do
          expandedDOpts="${expandedDOpts} -D${dopt/:/=}"
      done
fi

mcServerRunnerArgs="--stop-duration 60s"

if [[ ${TYPE} == "FEED-THE-BEAST" ]]; then
    if [ ! -e "${FTB_DIR}/ops.json" -a -e /data/ops.txt ]; then
      cp -f /data/ops.txt ${FTB_DIR}/
    fi

    if [ ! -e "${FTB_DIR}/whitelist.json" -a -e /data/white-list.txt ]; then
      cp -f /data/white-list.txt ${FTB_DIR}/
    fi

    cp -f /data/eula.txt "${FTB_DIR}/"

    cat > "${FTB_DIR}/settings-local.sh" <<EOF
export MIN_RAM="${INIT_MEMORY}"
export MAX_RAM="${MAX_MEMORY}"
export JAVA_PARAMETERS="${JVM_XX_OPTS} -Xms${INIT_MEMORY} ${JVM_OPTS} $expandedDOpts"
EOF

    # patch CurseForge cfg file, if present
    if [ -f "${FTB_DIR}/settings.cfg" ]; then
      sed -i "s/MAX_RAM=[^;]*/MAX_RAM=${MAX_MEMORY}/" "${FTB_DIR}/settings.cfg"
    fi

    cd "${FTB_DIR}"
    log "Running FTB ${FTB_SERVER_START} in ${FTB_DIR} ..."
    if isTrue ${DEBUG_EXEC}; then
      set -x
    fi
    exec mc-server-runner ${mcServerRunnerArgs} "${FTB_SERVER_START}"
else
  # If we have a bootstrap.txt file... feed that in to the server stdin
  if [ -f /data/bootstrap.txt ]; then
    bootstrapArgs="--bootstrap /data/bootstrap.txt"
  fi

  log "Starting the Minecraft server..."
  JVM_OPTS="-Xms${INIT_MEMORY} -Xmx${MAX_MEMORY} ${JVM_OPTS}"
  if isTrue ${DEBUG_EXEC}; then
    set -x
  fi
  exec mc-server-runner ${bootstrapArgs} ${mcServerRunnerArgs} java $JVM_XX_OPTS $JVM_OPTS $expandedDOpts -jar $SERVER "$@" $EXTRA_ARGS
fi
